package com.jason.www.service.impl;

import com.jason.www.commons.entity.GiftCardExcelBean;
import com.jason.www.commons.entity.GiftCardUpLoadExcelBean;
import com.jason.www.commons.exception.BusiException;
import com.jason.www.controller.vo.GiftCardVo;
import com.jason.www.dao.GiftCardMapper;
import com.jason.www.exception.CoreException;
import com.jason.www.pojo.GiftCard;
import com.jason.www.service.IGiftCardService;
import com.jason.www.util.ExcelParserStrategy;
import com.jason.www.util.ExcelParserStrategy.CellConfig;
import com.jason.www.util.PoiHelper;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 购物卡  服务实现类
 * </p>
 *
 * @author JasonChoi
 * @since 2018-09-13
 */
@Service
public class GiftCardServiceImpl implements IGiftCardService {
    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    GiftCardMapper giftCardMapper;

    @Override
    public void downloadGiftCardExcel(HttpServletResponse response, GiftCardVo vo) throws Exception {
        List<GiftCardExcelBean> result = new ArrayList<GiftCardExcelBean>();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("购物卡列表.xls", StandardCharsets.UTF_8.toString()));
        PoiHelper excelUtil = new PoiHelper();
        List<GiftCard> list = giftCardMapper.selectByCondition(new GiftCard());
        list.forEach(source -> {
            GiftCardExcelBean target = new GiftCardExcelBean();
            BeanUtils.copyProperties(source, target);
            result.add(target);
        });
        excelUtil.exportExcel(
                "购物卡列表",
                GiftCardExcelBean.getExcelFieldsHeaders(),
                result,
                response.getOutputStream(),
                GiftCardExcelBean.getExcelFieldsColumns());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String batchInsertByFile(InputStream ips, String fileName) throws BusiException {
        int count = 0;
        LinkedList<GiftCard> giftCards = new LinkedList<>();
        LocalDateTime beforeTime = LocalDateTime.now();
        ExcelParserStrategy strategy = getGiftCardStra();
        try {
            List<?> list = PoiHelper.readTable(ips, strategy, fileName);
            if(list.size() >18000){ throw new BusiException("上传的Excel文件条数不能大于18000条，请删减后再试");}
            for (Object object : list) {
                GiftCardUpLoadExcelBean upBean = (GiftCardUpLoadExcelBean) object;
                GiftCard giftCard = new GiftCard();
                BeanUtils.copyProperties(upBean,giftCard);
                //count += giftCardMapper.insert(giftCard);//"{\"msg\":\"耗时367957毫秒(约367秒)，成功插入条数：4296\",\"success\":true}"
                giftCards.add(giftCard);
            }
            //一次性最大插入量大概18000多条 可以通过修改my.ini的max_allowed_packet字段自行增大
            // mysql 中查询：SHOW VARIABLES LIKE '%max_allowed_packet%';
            count = giftCardMapper.batchSave(giftCards);//"{\"msg\":\"耗时2354毫秒(约2秒)，成功插入条数：4296\",\"success\":true}"
            Long betweenTime = Duration.between(beforeTime, LocalDateTime.now()).toMillis();
            return new StringBuffer("耗时").append(betweenTime).append("毫秒(约").append(betweenTime/1000).append("秒)，成功插入条数：").append(count).toString();
        } catch (IOException e) {
            throw new BusiException("上传文件异常", e);
        } catch (CoreException e) {
            throw new BusiException("上传文件失败：" + e.getMessage(), e);
        }finally {
        }
    }

    private ExcelParserStrategy getGiftCardStra() {
        ExcelParserStrategy strategy = new ExcelParserStrategy();
        String[] headers = GiftCardUpLoadExcelBean.getUploadExcelFieldsHeaders();
        strategy.setHeaderNames(headers);
        strategy.setHeaderStartRow((short) 1);
        strategy.setHeaderRowHeight((short) 1);
        strategy.setHeaderStartCol(0);//对应excel表的表头ABCD...
        strategy.setHeaderEndCol(GiftCardUpLoadExcelBean.getUploadExcelFieldsHeaders().length-1);
        strategy.setClazz(GiftCardUpLoadExcelBean.class);
        List<CellConfig> arr = new ArrayList<CellConfig>(headers.length);
        arr.add(new CellConfig(Cell.CELL_TYPE_NUMERIC,GiftCardUpLoadExcelBean.ID,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_STRING,GiftCardUpLoadExcelBean.CARDNO,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_NUMERIC,GiftCardUpLoadExcelBean.PRICE,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_STRING,GiftCardUpLoadExcelBean.LICENSE,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_BOOLEAN,GiftCardUpLoadExcelBean.ACTIVE,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_STRING,GiftCardUpLoadExcelBean.MOBILE,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_STRING,GiftCardUpLoadExcelBean.DITCH,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_NUMERIC,GiftCardUpLoadExcelBean.EXPIRE_TIME,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_NUMERIC,GiftCardUpLoadExcelBean.CREATE_TIME,false));
        arr.add(new CellConfig(Cell.CELL_TYPE_NUMERIC,GiftCardUpLoadExcelBean.LICENSE_TIME,false));
        strategy.setCells(arr.toArray(new CellConfig[0]));
        return strategy;
    }


}
